package com.cy.guavaRetry;

import com.alibaba.fastjson.JSON;
import com.github.rholder.retry.*;
import lombok.extern.slf4j.Slf4j;
import org.testng.annotations.Test;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author yue.cao
 * @since 12-23-2020
 */
@Slf4j
public class GuavaRetryDemo {

	@Test
	public void t1() {
		Retryer<Boolean> retry = RetryerBuilder.<Boolean>newBuilder()
				.retryIfException()
				// 定长时间的重试
				// .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
				.withWaitStrategy(WaitStrategies.incrementingWait(1, TimeUnit.SECONDS, 5, TimeUnit.SECONDS))
				.withStopStrategy(StopStrategies.stopAfterAttempt(3))
				.build();
		Boolean res = null;
		try {
			res = retry.call(new Callable<Boolean>() {
				@Override
				public Boolean call() throws Exception {
					log.warn("<== start method ==>");
					int test = 1 / 0;
					return true;
				}
			});
			// 这个是说明 抛出了意料之外的异常 如果你定义了指定异常
		} catch (ExecutionException e) {
			log.error("ExecutionException ===>", e);
		} catch (RetryException e) {
			log.error("RetryException ===>", e);
		}
		System.out.println(res);

	}

	@Test
	public void t2() throws ExecutionException, RetryException {
		Retryer<Boolean> retry = RetryerBuilder.<Boolean>newBuilder()
				.withStopStrategy(StopStrategies.stopAfterAttempt(3))
				.retryIfException( exception-> {
					boolean instance = Objects.requireNonNull(exception).getClass().isInstance(NullPointerException.class);
					return !instance;
				})
				.build();

		retry.call(new Callable<Boolean>() {
			@Override
			public Boolean call() throws Exception {
				System.out.println("in");
				if (1==1){
					throw new NullPointerException(" ");
				}
				return null;
			}
		});
	}

	private static final Retryer<Boolean> salesApiRetry = RetryerBuilder.<Boolean>newBuilder()
			.retryIfException()
			.withWaitStrategy(WaitStrategies.fixedWait(20, TimeUnit.MILLISECONDS))
			.withStopStrategy(StopStrategies.stopAfterAttempt(3))
			.withRetryListener(new RetryListener() {
				@Override
				public <V> void onRetry(Attempt<V> attempt) {
					if (attempt.hasException()) {
						log.warn("nowNum:{} reason:{}", attempt.getAttemptNumber(), attempt.getExceptionCause().toString());
					} else {
						log.warn("nowNum:{} reason:{}", attempt.getAttemptNumber(), JSON.toJSONString(attempt.getResult()));
					}
				}
			}).build();


	@Test
	public void t1111() throws ExecutionException, RetryException {
		salesApiRetry.call(new Callable<Boolean>() {
			@Override
			public Boolean call() throws Exception {
				System.out.println("ininin");
				System.out.println(1/0);
				return true;
			}
		});

		System.out.println("============");

	}


}
